package com.google.code.motoo.sample;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.Socket;
import java.util.Date;

import com.google.code.motoo.codec.serialization.SerializationUtils;
import com.google.code.motoo.core.IoBuffer;

public class Client {
    Socket socket;
    DataInputStream in;
    java.io.DataOutputStream out;
    
    public void start() {
    	try {
    		socket = new Socket("127.0.0.1", 9000);
			out = new DataOutputStream(socket.getOutputStream());
    		while (true) {
				
				String str = "InputStreamReader";
				writeDate(str);
//				out.println("InputStreamReader\\r\\n");
				
				print();
				Thread.sleep(2000);
				
//				out.println("你好啊，不错哦\\r\\n");
//				out.flush();
//				print();
				long l = 1234576;
				writeDate(new Date());
				print();
				Thread.sleep(2000);
			}
//    		
//    		out.close();
//			in.close();
//			socket.close();
    		
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public void writeDate(Serializable object) throws Exception {
    	byte[] array = SerializationUtils.encodeToByteArray(object);
		int length = array.length;
		IoBuffer buffer = IoBuffer.allocate(length + 4);
		buffer.putInt(length);
		buffer.put(array);
		buffer.flip();
		out.write(buffer.array());
		out.flush();
    }
    
    public static byte[] encodeToByteArray(Serializable object) {
		ByteArrayOutputStream bo = new ByteArrayOutputStream();
		ObjectOutputStream oo = null;
		try {
			oo = new ObjectOutputStream(bo);
			oo.writeObject(object);

			return bo.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();

			return null;
		} finally {
			if (oo != null) {
				try {
					oo.close();
				} catch (IOException e) {
				}
			}
		}

	}
    
    private void print() throws IOException {
    	in = new DataInputStream(socket.getInputStream());
    	byte[] b = new byte[512];
    	in.read(b);
		IoBuffer a = IoBuffer.allocate(1024);
		a.put(b);
		a.flip();
		int dataLength = a.getInt();
		
		IoBuffer buffer = IoBuffer.allocate(dataLength);
		buffer.put(a, 4, dataLength);
		buffer.flip();
		Object message = SerializationUtils.decodeFromByteArray(buffer.array());
		System.out.println(message);
    }

    public Client() {
        
    }

    public static void main(String[] args) {
        new Client().start();
    }
} 